package cn.crawler.app.crown.commons.websocket.main.base;

import cn.crawler.app.crown.modules.models.constant.Fields;
import cn.crawler.app.netty.modules.models.NettyConstant;
import cn.crawler.framework.util.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import lombok.Data;
import org.nutz.lang.Strings;

/**
 * @author 22099
 */
@Data
public class NettyRouter {

    private static final JSONObject empty = new JSONObject(0);

    private Channel income;

    private String uri;

    private JSONObject params = empty;

    private String[] uriPart;


    public NettyRouter(String uri) {
        this.setUri(uri);
    }

    public NettyRouter(String uri, Channel income) {
        this.setUri(uri);
        this.income = income;
    }

    public void setUri(String uri) {
        //包含参数-识别
        if (uri.contains("?")) {
            String[] split = uri.split("\\?");
            this.uri = split[0];
            this.uriPart = split[0].split("/");

            //参数解析
            if (Strings.isNotBlank(split[1])) {
                //json
                if (split[1].startsWith("{")) {
                    params = JSONUtil.parseToJSON(split[1]);
                }
                //url
                else {
                    setParams(split[1]);
                }
            }
        } else {
            this.uri = uri;
        }
    }

    public void setParams(String paramStr) {
        if ( null != paramStr && paramStr.length()>0) {
            String[] paramStrings = paramStr.split("&");
            params = new JSONObject(paramStrings.length);
            for (String param : paramStrings) {
                String[] strings = param.split("=");
                params.put(strings[0], strings.length == 2 ? strings[1] : null);
            }
        }
    }

    public void setParam(String key,Object val) {
        if (params == null) {
            params = new JSONObject();
        }
        params.put(key,val);
    }



    public String getSubscribeParam() {
        return params.getString(NettyConstant.SUBSCRIBE);
    }

    public String getSubscribeKey() {
        return uri + ":" + params.get(NettyConstant.SUBSCRIBE).toString();
    }


    public String getUriPart(int index) {
        if (this.uriPart.length <= index) {
            return null;
        }
        return uriPart[index];
    }

    public Object getParam(String key) {
        return this.getParams().get(key);
    }

    public String getCallBackParam() {
        return this.getParams().getString(Fields.CALL_BACK_PARAM);
    }
}
